package com.magictower.primary.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.format.Formatter;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.magictower.primary.R;
import com.magictower.primary.adapter.AppManagerAdapter;
import com.magictower.primary.bean.AppInfo;
import com.magictower.primary.engine.AppInfoParser;

import java.util.ArrayList;
import java.util.List;

public class AppManagerActivity extends AppCompatActivity implements View.OnClickListener {

    @ViewInject(R.id.list_view)
    private ListView listView;
    @ViewInject(R.id.tv_rom)
    private TextView tv_rom;
    @ViewInject(R.id.tv_sd)
    private TextView tv_sd;
    @ViewInject(R.id.tv_app)
    private TextView tv_app;
    private List<AppInfo> userAppInfos;
    private List<AppInfo> systemAppInfos;

    private PopupWindow popupWindow;
    private AppInfo clickAppInfo;
    private UninstallReceiver receiver;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_app_manager);
        ViewUtils.inject(this);

        initUI();
        initData();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            AppManagerAdapter adapter = new AppManagerAdapter(AppManagerActivity.this, userAppInfos, systemAppInfos);
            // 加载至ListView中
            listView.setAdapter(adapter);
        }
    };

    private void initUI() {
        // 获取rom内存剩余空间
        long rom_freeSpace = Environment.getDataDirectory().getFreeSpace();
        //获取外部存储剩余空间
        long sd_freeSpace = Environment.getExternalStorageDirectory().getFreeSpace();
        // 格式化大小
        tv_rom.setText("内存可用:" + Formatter.formatFileSize(this, rom_freeSpace));
        tv_rom.setSingleLine();
        tv_sd.setText("sd卡可用:" + Formatter.formatFileSize(this, sd_freeSpace));
        tv_sd.setSingleLine();

        receiver = new UninstallReceiver();
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
        intentFilter.addDataScheme("package");
        registerReceiver(receiver, intentFilter);

        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }
            /**
             * @param view
             * @param firstVisibleItem 第一个可见的条的位置
             * @param visibleItemCount 一页可以展示多少个条目
             * @param totalItemCount   总共的item的个数
             */
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                popupWindowDismiss();
                if (systemAppInfos != null && userAppInfos != null) {
                    if (firstVisibleItem > (userAppInfos.size() + 1)) {
                        tv_app.setText("系统程序（"+ systemAppInfos.size() +"）个");
                    } else {
                        tv_app.setText("用户程序（"+ userAppInfos.size() +"）个");
                    }
                }
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //获取当前点击的对象
                Object obj = listView.getItemAtPosition(position);
                if(obj != null && obj instanceof AppInfo) {
                    clickAppInfo = (AppInfo) obj;

                    View contentView = View.inflate(AppManagerActivity.this, R.layout.item_popup, null);
                    LinearLayout ll_uninstall = (LinearLayout) contentView.findViewById(R.id.ll_uninstall);
                    LinearLayout ll_start = (LinearLayout) contentView.findViewById(R.id.ll_start);
                    LinearLayout ll_share = (LinearLayout) contentView.findViewById(R.id.ll_share);
                    LinearLayout ll_detail = (LinearLayout) contentView.findViewById(R.id.ll_detail);

                    ll_uninstall.setOnClickListener(AppManagerActivity.this);
                    ll_start.setOnClickListener(AppManagerActivity.this);
                    ll_share.setOnClickListener(AppManagerActivity.this);
                    ll_detail.setOnClickListener(AppManagerActivity.this);

                    popupWindowDismiss();//有弹窗就关掉
                    //-2 表示包裹内容
                    popupWindow =  new PopupWindow(contentView, -2, -2);
                    // 需求注意， 使用PopupWindow必须使用背景，才有动画效果
                    popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

                    int[] location = new int[2];
                    //获取view展示到窗体上面
                    view.getLocationInWindow(location);

                    popupWindow.showAtLocation(parent, Gravity.TOP | Gravity.LEFT, 70, location[1]);

                    ScaleAnimation animation = new ScaleAnimation(0.5f, 1.0f, 0.5f, 1.0f,
                            Animation.RELATIVE_TO_PARENT, 0.1f, Animation.RELATIVE_TO_PARENT, 0.5f);
                    animation.setDuration(300);
                    contentView.startAnimation(animation);

                }
            }
        });
    }

    private void initData() {
        new Thread() {
            @Override
            public void run() {
                List<AppInfo> appInfo = AppInfoParser.getAppInfos(AppManagerActivity.this);
                userAppInfos = new ArrayList<>();
                systemAppInfos = new ArrayList<>();
                for (AppInfo info : appInfo) {
                    if (info.isUserApp()) {
                        userAppInfos.add(info);
                    } else {
                        systemAppInfos.add(info);
                    }
                }
                handler.sendEmptyMessage(0);
            }
        }.start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_uninstall :
                Intent uninstall_intent = new Intent("android.intent.action.DELETE", Uri.parse("package:" + clickAppInfo.getApkPackageName()));
                startActivity(uninstall_intent);
                popupWindowDismiss();
                break;
            case R.id.ll_start :
                Intent start_intent = getPackageManager().getLaunchIntentForPackage(clickAppInfo.getApkPackageName());
                startActivity(start_intent);
                popupWindowDismiss();
                break;
            case R.id.ll_share :
                Intent share_intent = new Intent("android.intent.action.SEND");
                share_intent.setType("text/plain");
                share_intent.putExtra("android.intent.extra.SUBJECT", "分享");
                share_intent.putExtra("android.intent.extra.TEXT",
                        "Hi！推荐您使用软件：" + clickAppInfo.getApkName()+"。下载地址:"+"https://play.google.com/store/apps/details?id="+clickAppInfo.getApkPackageName());
                startActivity(Intent.createChooser(share_intent, "分享"));
                popupWindowDismiss();
                break;
            case R.id.ll_detail :
                Intent detail_intent = new Intent();
                detail_intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                detail_intent.addCategory(Intent.CATEGORY_DEFAULT);
                detail_intent.setData(Uri.parse("package:" + clickAppInfo.getApkPackageName()));
                startActivity(detail_intent);
                popupWindowDismiss();
                break;
        }
    }

    private class UninstallReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println("接收到卸载的广播");
            if (clickAppInfo.isUserApp()) {
                userAppInfos.remove(clickAppInfo);
            } else {
                systemAppInfos.remove(clickAppInfo);
            }
            handler.sendEmptyMessage(0);
        }
    }

    private void popupWindowDismiss() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
            popupWindow = null;
        }
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(receiver);
        popupWindowDismiss();
        super.onDestroy();
    }
}
